package com.woniumall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniumall.dao.*;
import com.woniumall.pojo.*;
import com.woniumall.service.AddressService;
import com.woniumall.service.OrderService;
import com.woniumall.util.sqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @auther linke
 * @create 2021-10-29 16:52
 */

public class OrderServiceImpl implements OrderService {
    private  SqlSession sqlSession = null;


    @Override
    public PayInfor createOrder(User user, List<Cart> mycart, int addressid) {
        sqlSession = sqlSessionUtil.sqlSession();
      OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
      OrderItemDao orderItemDao = sqlSession.getMapper(OrderItemDao.class);
      GoodsDao goodsDao = sqlSession.getMapper(GoodsDao.class);
      AddressDao addressDao = sqlSession.getMapper(AddressDao.class);
      CartDao cartDao = sqlSession.getMapper(CartDao.class);
        //订单号生成
        String orderno = user.getId()+"u"+System.currentTimeMillis()+"";
        //获取时间
        DateFormat df3 = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINA);
        DateFormat df7 = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CHINA);
        String day = df3.format(new Date());
        String hour = df7.format(new Date());
        //计算订单总价
        BigDecimal total = new BigDecimal("0");
        for (Cart cart : mycart) {
            BigDecimal nums = new BigDecimal(cart.getNums()+"");
            total = total.add(cart.getPrice().multiply(nums));
        }
        //查询地址信息
        Address address = addressDao.findById(addressid);
        //创建订单对象
        Order order = new Order();
        order.setOrderno(orderno);
        order.setUserid(user.getId());
        order.setOrdertime(day+hour);
        order.setAccept(address.getAccept());
        order.setTelphone(address.getTelphone());
        order.setAddress(address.getProvince()+address.getCity()+address.getArea()+address.getAddress());
        order.setMoney(total);
        order.setStatus("1");
        //插入订单
        int row = orderDao.insertOrder(order);
        PayInfor payInfor = new PayInfor();
        if(row < 1){//判断订单是否创建成功
            //sqlSession.close();
            orderDao.del(orderno);//删除刚才创建的订单
            sqlSession.commit();
            payInfor.setMassage("订单创建失败!请联系客服");
            payInfor.setFlag(false);//失败状态
            return  payInfor;
        }
        //数据校验
        //价格与数据库是否一致，库存
        for (Cart cart : mycart) {
           // System.out.println(cart);
            int goodsid =  cart.getGoodsid();
            Goods goods = goodsDao.findStockSalesPriceById(goodsid);
            System.out.println(goods);
            boolean flag = goods.getSalesprice().equals(cart.getPrice());
            //检查每一个商品是否变动
            if(!flag){
                orderDao.del(orderno);//删除刚才创建的订单
                sqlSession.commit();
                payInfor.setMassage(goods.getName()+"价格发生变动，由："+cart.getPrice()+"元变更为："+goods.getSalesprice()+"元");
                cart.setPrice(goods.getSalesprice());//变更购物车的价格
                //sqlSession.close();
                payInfor.setFlag(false);//失败状态
                return payInfor;
            }
            //检查库存是否足够
            int goodsstock = goods.getStock()-cart.getNums();
            if(goodsstock<0){
                orderDao.del(orderno);//删除刚才创建的订单
                sqlSession.commit();
                payInfor.setMassage(goods.getName()+"库存不足，当前只有："+goods.getStock()+"件，你要购买："+cart.getNums()+"件，已将购买数量变更为最大库存数");
                cart.setNums(goods.getStock());//变更购物车的数量为最大数量
                //sqlSession.close();
                payInfor.setFlag(false);//失败状态
                return payInfor;
            }
            //更新库存
            goodsDao.updateStockById(goodsstock,goods.getId());

            //根据订单号查询订单id
            int byOrderno = orderDao.findByOrderno(orderno);
            //插入订单项表
            int insertOrderItem = orderItemDao.insertOrderItem(new OrderItem(byOrderno,goodsid,cart.getNums(),cart.getPrice()));
            if(insertOrderItem < 1){
                orderItemDao.del(orderno);//删除刚才创建的订单项
                sqlSession.commit();
                payInfor.setMassage(goods.getName()+"订单项创建失败，请联系客服！");
                //sqlSession.close();
                payInfor.setFlag(false);//失败状态


                sqlSession.close();//释放资源
                return payInfor;
            }
        }
        //删除数据库中的订单
        for (Cart cart : mycart) {
            cartDao.removeByCartId(cart.getId());
        }
        mycart.clear();//移除session 中购物车的所有元素

        sqlSession.commit();
        payInfor.setMassage("订单创建成功请进行支付！一共需要支付："+total+"元！");
        payInfor.setOrderNumber(user.getUsername()+"账号订单："+orderno+"支付");
        payInfor.setName("支付宝");
        payInfor.setTotalPrice(total);
        payInfor.setFlag(true);//最后成功状态
        sqlSession.close();//关闭资源
        return payInfor;
    }
    //我的订单分页查询
    @Override
    public PageInfo<Order> findAllOrder(int currentPage,int userid) {
        sqlSession = sqlSessionUtil.sqlSession();
        OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
        //设置起始索引的显示个数
        PageHelper.startPage(currentPage,6);
        List<Order> list = orderDao.findAllOrder(userid);
        PageInfo<Order> lists = new PageInfo<>(list);
        System.out.println(lists);
        sqlSession.close();
        return lists;
    }
    //查询订单基本信息
    @Override
    public Order findOrderById(int orderId) {
        sqlSession = sqlSessionUtil.sqlSession();
        OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
        Order order = orderDao.findOrderById(orderId);
        System.out.println(order);
        sqlSession.close();
        return order;
    }
    //查询订单相关书籍详情信息
    @Override
    public List<OrderItem> findOrderItemById(int orderId) {
        sqlSession = sqlSessionUtil.sqlSession();
        OrderItemDao orderItemDao = sqlSession.getMapper(OrderItemDao.class);

        List<OrderItem> orderItemList = orderItemDao.findOrderItemById(orderId);
        System.out.println(orderItemList);
        sqlSession.close();
        return orderItemList;
    }
    //删除订单和更新库存
    @Override
    public int delOrderAndUodateGoodsNum(String orderno) {
        sqlSession = sqlSessionUtil.sqlSession();
        OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
        GoodsDao goodsDao = sqlSession.getMapper(GoodsDao.class);
        OrderItemDao orderItemDao = sqlSession.getMapper(OrderItemDao.class);
        int orderid = orderDao.findByOrderno(orderno);//得到订单id
        int newStock = 0;//商品库存

      /*  Goods goods = goodsDao.findById(goodsid);//获取书籍信息*/
        List<OrderItem> orderItemList = orderItemDao.findOrderItemById(orderid);//根据订单号查询订单项表中所关联的书籍信息
        for (OrderItem orderItem : orderItemList) {//遍历订单项表
            Goods good = orderItem.getGoods();
            newStock = good.getStock() + orderItem.getGoodsnum();//将订单取消的书籍数量加回数据库
            goodsDao.updateStockById(newStock,good.getId());//根据id更新库存
            sqlSession.commit();
            newStock = 0;//重置为0
        }
        /*OrderItem orderItem = orderItemDao.findOrderItemsById(orderid);//获取订单项表*/
     /*   newStock = goods.getStock() + orderItem.getGoodsnum();//将订单取消的书籍数量加回数据库

        goodsDao.updateStockById(newStock,goodsid);//根据id更新库存*/
        int row = orderDao.del(orderno);//根据订单号删除订单
        sqlSession.commit();
        sqlSession.close();//释放资源
        return row;
    }
}
